package com.hits.buildqrcode.service;

import com.alibaba.fastjson.JSONObject;
import com.hits.buildqrcode.config.HttpClient;
import com.hits.buildqrcode.domian.ParamApp;
import com.hits.buildqrcode.domian.SfjdQrcodeRecord;
import com.hits.buildqrcode.mapper.SfjdQrcodeRecordMapper;
import com.hits.buildqrcode.mapper.SfjdSldjMapper;
import com.hits.buildqrcode.util.DateUtil;
import com.hits.buildqrcode.utils.ImageUtils;
import com.spire.doc.documents.HorizontalAlignment;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class CaseService {

    private static Logger logger  = LoggerFactory.getLogger(CaseService.class);

    final static String SAVE_QR_PATH_PREFIX = "D:/upload/qr/";

    public static String qrCodePath;

    @Autowired
    private SfjdSldjMapper sldjMapper;

    @Autowired
    private ParamApp paramApp;

    @Autowired
    private SfjdQrcodeRecordMapper sfjdQrcodeRecordMapper;

    public JSONObject getCase(String data,String status) {
        try {
            JSONObject jsonObject = this.sldjMapper.getCase(data,status);

            return jsonObject;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 功能描述: 查询所有状态为待签发，待送达，待归档，已归档，
     * 复核时间为9-2号以后得未赋码得数据
     * @param data 配置得复核时间(9-2)
     * @param status 开关状态 1开启状态
     * @return com.alibaba.fastjson
     */
    public List<JSONObject> getUncodedData(String data,String status){
        List<JSONObject> jsonObject = null;
        try {
            jsonObject = sldjMapper.selectUncodedData(data,status);
        }catch (Exception e){
            e.printStackTrace();
        }
        return jsonObject;
    }

    /**
     * 功能描述:根据案件信息获取二维码数据
     * @return com.alibaba.fastjson
     */
    public synchronized JSONObject getQrCodeDateByInfo() {
        /* 返回案件id */
        JSONObject paramObject = new JSONObject();
        String ajid = "";
        try {
            /* 根据复核时间筛选案件 取配置信息*/
            com.alibaba.fastjson.JSONObject configObj = sldjMapper.getConfigurationInformation();
            String signparam = configObj.getString("SIGNPARAM");
            String status = configObj.getString("STATUS");
            if (Objects.equals("1",status)){
                List<JSONObject> uncodedData = getUncodedData(signparam, status);
                if (!Objects.equals(null,uncodedData) && uncodedData.size()>0){
                    for (int i = 0; i < uncodedData.size(); i++) {
                        ajid = uncodedData.get(i).getString("xxbh");
                        String wtr = uncodedData.get(i).getString("wtr");
                        System.out.println("==========================="+wtr);
                        if (Objects.equals(null,wtr) || Objects.equals("",wtr)){
                            uncodedData.get(i).put("wtr",uncodedData.get(i).getString("WTRXM"));
                        }
                        String ajbc = uncodedData.get(i).getString("ajbc");
                        /* 重新鉴定是由处理 */
                        String cxjdsy = uncodedData.get(i).getString("cxjdsy")!=null?uncodedData.get(i).getString("cxjdsy"):"无";
                        /* 申请人姓名处理 */
                        String lxr = uncodedData.get(i).getString("lxr") != null ? uncodedData.get(i).getString("lxr") : "无";
                        uncodedData.get(i).put("lxr",lxr);
                        uncodedData.get(i).put("cxjdsy",cxjdsy);
                        /* 鉴定对象类型处理 */
                        int jddxlx = uncodedData.get(i).getString("jddxlx").equals("1")?0:1;
                        uncodedData.get(i).put("jddxlx",jddxlx);
                        if (ajbc.indexOf("2")!=-1){
                            uncodedData.get(i).put("cxjdsy",cxjdsy);
                        }else {
                            uncodedData.get(i).put("cxjdsy","无");
                        }
                        String new_wtrsd = "";
                        if (uncodedData.get(i).getString("wtrsd").length()>20){
                            new_wtrsd = uncodedData.get(i).getString("wtrsd").substring(0,19);
                        }else {
                            new_wtrsd = uncodedData.get(i).getString("wtrsd");
                        }
                        if (uncodedData.get(i).getString("jdsx")==null || uncodedData.get(i).getString("jdsx").equals("")){
                            uncodedData.get(i).put("jdsx","无");
                        }
                        uncodedData.get(i).put("lxdz",new_wtrsd);
                        uncodedData.get(i).put("wtrsd",new_wtrsd);
                        uncodedData.get(i).put("sftgsfjdyz",ajbc.indexOf("1")!=-1?1:0);
                        uncodedData.get(i).put("sfbcjd",ajbc.indexOf("3")!=-1?1:0);
                        uncodedData.get(i).put("sfsycxjd",ajbc.indexOf("2")!=-1?1:0);
                        uncodedData.get(i).put("yzje",(ajbc.indexOf("1")!=-1 &&uncodedData.get(i).getString("yzje")!=null)?uncodedData.get(i).getString("yzje"):0);
                        net.sf.json.JSONObject paramJsonObject = net.sf.json.JSONObject.fromObject(paramApp);
                        /* 获取token */
                        String token = TokenService.token;
                        paramJsonObject.put("token",token);
                        /* 鉴定对象信息 */
                        List<JSONObject> renList = this.sldjMapper.getJddxRen(ajid);
                        List<JSONObject> jddxWu = this.sldjMapper.getJddxWu(ajid);
                        List<JSONObject> jddxChe = this.sldjMapper.getJddxChe(ajid);
                        renList.addAll(jddxWu);
                        renList.addAll(jddxChe);
                        String jddx = JSONObject.toJSONString(renList);
                        if (jddx.length()>500){
                            jddx = jddx.substring(0,500);
                        }
                        uncodedData.get(i).put("jddx",jddx);
                        /* 机构信息 */
                        JSONObject unitByAjid = this.sldjMapper.getUnitByAjid(ajid);
                        uncodedData.get(i).put("sfjdjgmc",unitByAjid!=null?unitByAjid.getString("sfjdjgmc"):"无");
                        uncodedData.get(i).put("tyshxydm",unitByAjid!=null?unitByAjid.getString("tyshxydm"):"无");
                        uncodedData.get(i).put("qybm",unitByAjid!=null?unitByAjid.getString("qybm"):"无");
                        uncodedData.get(i).put("qymc",unitByAjid!=null?unitByAjid.getString("qymc"):"无");
                        uncodedData.get(i).put("sfjdajjgah",unitByAjid!=null?unitByAjid.getString("tyshxydm"):"无");
                        /* 鉴定意见信息 */
                        List<String> jdyjByAjid = this.sldjMapper.getJdyjByAjid(ajid);
                        String join = StringUtils.join(jdyjByAjid, ",");
                        /* 鉴定意见长度太长可能导致获取二维码失败需要截取 */
                        if (join.length()>100){
                            join = join.substring(0,100);
                        }
                        uncodedData.get(i).put("jdyj",join);
                        /* 其他信息 */
                        JSONObject infoByAjid = this.sldjMapper.getInfoByAjid(ajid);
                        uncodedData.get(i).put("wsfhr",infoByAjid.getString("wsfhr"));
                        uncodedData.get(i).put("wsqfr",infoByAjid.getString("wsqfr"));
                        uncodedData.get(i).put("cjwsfs",infoByAjid.getString("cjwsfs"));
                        uncodedData.get(i).put("cjjdyjsj",infoByAjid.getString("cjjdyjsj"));
                        uncodedData.get(i).put("sjcjsj",infoByAjid.getString("sjcjsj"));
                        uncodedData.get(i).put("sjzhycgxsj",infoByAjid.getString("sjzhycgxsj"));
                        uncodedData.get(i).put("sfyqjd",infoByAjid.getString("sfyqjd"));
                        uncodedData.get(i).put("ywpqzj",infoByAjid.getString("ywpqzj"));
                        /* 将主表信息封装 */
                        paramJsonObject.put("body",uncodedData.get(i).toString());
                        System.out.println(paramJsonObject.toString());
                        String qrCodeJson = HttpClient.getCodeToInterFace(paramJsonObject.toString());
                        /* 将json字符串转为json对象 */
                        net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(qrCodeJson);
                        String qrCode = (String) jsonObject.get("data");
                        String code = jsonObject.getString("code");
                        String message = jsonObject.getString("message");
                        if (message.equals("无效的token") && !code.equals("200")){
                            TokenService.getTokenToInterFace();
                            JSONObject data = new JSONObject();
                            data.put("code",code);
                            data.put("ajid",ajid);
                            data.put("message",jsonObject.getString("message"));
                            return data;
                        }
                        /* 存储二维码路径 */
                        qrCodePath = SAVE_QR_PATH_PREFIX+ DateUtil.getToday()+"/"+DateUtil.getCruenntHousrTime()+"/"+UUID.randomUUID().toString().replaceAll("-","")+".jpg";
                        ImageUtils.base64StrToImage(qrCode,qrCodePath);
                        if (Objects.equals("200",code)){
                            /* 根据案件id获取文书 */
                            boolean flag = insertQrCodeWord(ajid);
                            if (flag){
                                /* 修改主表赋码状态 */
                                sldjMapper.updateCodeStatus(ajid);
                            }
                        }else {
                            qrCodePath = "";
                        }
                        /* 保存日志记录 */
                        addQrcodeRecode(ajid,qrCodePath,code,message);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            paramObject.put("ajid",ajid);
            paramObject.put("code",500);
            paramObject.put("message",e.getMessage());
        }
        return paramObject;
    }

    /**
     * 功能描述：添加二维码生成记录
     * @param ajid 案件id
     * @param path  二维码路径
     * @param code  获取二维码状态 0：成功 1：失败
     * @param message 获取二维码信息
     */
    public void addQrcodeRecode(String ajid, String path,String code, String message) {
        try {
            //byte[] bytes=null;
            int state = code.equals("200") ? 0 : 1;
            /*if (state==0){
                bytes = ImageUtils.image2byte(path);
            }*/
            SfjdQrcodeRecord.SfjdQrcodeRecordBuilder recordBuilder = SfjdQrcodeRecord.builder().
                    ajid(ajid).id(UUID.randomUUID().toString().replace("-", ""))
                    .createTime(new Date()).state(state).message(message).qrCodePath(path);
            this.sfjdQrcodeRecordMapper.insert(recordBuilder.build());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 功能描述:二维码插入鉴定意见书
     * @param ajid  案件id
     */
    public boolean insertQrCodeWord(String ajid){
        try {
            if (!Objects.equals(null,ajid) && !Objects.equals("",ajid)){
                /* 根据案件id获取文书 */
                String files = this.sldjMapper.getFiles(ajid);
                /* 循环插入二维码 */
                ImageUtils.insertPictureInHeaderByLocation(ajid, "D:\\upload\\" + files, qrCodePath, "",
                        60f, 60f);
                return true;
            }else {
                return false;
            }
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

}
